﻿using System.Collections.Generic;
using System.Linq;
using OpenRasta.IO;
using OpenRasta.Web;
using umbraco.cms.businesslogic.media;

namespace uREST.CMS.Extensions
{
    public static class MediaExtensions
    {
        public static Resources.Media ToResource(this Media media)
        {
            var resource = new Resources.Media
            {
                Id = media.Id,
                Href = typeof(Resources.Media).CreateUri("Media", new { id = media.Id }).ToString(),
                ParentId = media.ParentId,
                ParentHref = media.ParentId > 0 ? typeof(Resources.Media).CreateUri("Media", new { id = media.ParentId }).ToString() : "",
                Name = media.Text,
                MediaTypeAlias = media.ContentType.Alias,
                HasChildren = media.HasChildren,
                ChildrenHref = media.HasChildren ? typeof(List<Resources.Media>).CreateUri("MediaList", new { parentId = media.Id }).ToString() : ""
            };

            foreach (var property in media.GenericProperties)
            {
                resource.Properties.Add(new Resources.Property
                {
                    Key = property.PropertyType.Alias,
                    Value = property.Value == System.DBNull.Value ? null : property.Value
                });
            }

            return resource;
        }

        public static List<Resources.Media> ToResourceList(this Media[] mediaList)
        {
            return new List<Media>(mediaList).ToResourceList();
        }

        public static List<Resources.Media> ToResourceList(this List<Media> mediaList)
        {
            var resourceList = new List<Resources.Media>();
            resourceList.AddRange(mediaList.Select(media => media.ToResource()));
            return resourceList;
        }
    }
}
